import Notification from '/@/utils/notification'
import {buildParamsSignStr} from "/@/utils/format";
import {Session} from "/@/utils/storage";
import {ElMessage} from "element-plus";

export default {
    init() {
        const appId = import.meta.env.VITE_APP_ID;
        const token = Session.get('token');
        const socket = new WebSocket('wss://api.wocoding.cn/websocket?appId=' + appId + '&token=' + token);
        socket.onclose = () => {
            let _this = this;
            setTimeout(() => {
                _this.init();
            }, 3000)
        }
        socket.onerror = (err) => {
            let _this = this;
            setTimeout(() => {
                _this.init();
            }, 3000)
        }
        socket.onmessage = (response) => {
            const _data = response.data
            if (_data) {
                const _msg = JSON.parse(_data)
                switch (_msg.type) {
                    case 'notice':
                        Notification.handleNotification(_msg.title, _msg.title);
                        break;
                    case 'open':
                        ElMessage.success(_msg.msg)
                        break;
                    case 'task':
                        break;
                    case 'other':
                        console.log(_msg.msg)
                        break;
                    case 'error':
                        ElMessage.error(_msg.msg)
                        break;
                }
            }
        }
        socket.onopen = () => {
            let _data = {
                hello: 'hello',
                world: 'world',
                _time: new Date().getTime().toString()
            };
            _data.sign = buildParamsSignStr(_data)
            socket.send(JSON.stringify(_data) + '\r\n')
        }
    }
}
